[1, 2, 3, 4, 5, 6]
Feb 9, 2024
ndarray will create a new array and delete the original.Numpy array is a powerful N-dimensional array object which is in the form of rows and columns. We can initialize numpy arrays from nested Python lists and access it elements. In order to perform these numpy operations.
NdArray
Vectorization
Vectorization describes the absence of any explicit looping, indexing etc; in the code-these things are taking place, of course, just behind the scenes in optimized, pre-compiled C code.
Broadcasting
The term broadcasting describes how NumPy treats arrays with different shapes during arithmetic operations. Subject to certain constrains, the smaller array is “broadcast” across the larger array so that they have compatible shapes.
Use the following import convention
import time
import sys
SIZE = 1000000
L1 = range(SIZE)
L2 = range(SIZE)
A1 = np.arange(SIZE)
A2 = np.arange(SIZE)
start= time.time()
result=[(x,y) for x,y in zip(L1,L2)]
# time in ms
print((time.time()-start)*1000)
start = time.time()
result = A1+A2
# time in ms
print((time.time()-start)*1000)226.06158256530762
31.348228454589844
When you print an array, NumPy displays it in a similar way to nested lists, One-dimensional arrays are then printed as rows, bidimensionals as matrices and tridimensionals as lists of matrices.
If an array is too large to be printed, NumPy automatically skips the central part of the array and only prints the corners
array.sizearray.shapearray.dtypearray.astype(dtype)
array.tolist()[0.0,
5.2631578947368425,
10.526315789473685,
15.789473684210527,
21.05263157894737,
26.315789473684212,
31.578947368421055,
36.8421052631579,
42.10526315789474,
47.36842105263158,
52.631578947368425,
57.89473684210527,
63.15789473684211,
68.42105263157896,
73.6842105263158,
78.94736842105263,
84.21052631578948,
89.47368421052633,
94.73684210526316,
100.0]
np.info(np.function)
zeros()np.zeros(shape, dtype)
ones()np.ones(shape, dtype)
Note - Rows = 3 - Columns = 4
arange()np.arange(start, stop, step)
linspace()np.linspace(start, stop, num, dtype, retstep)
[0. 0.25 0.5 0.75 1. 1.25 1.5 1.75 2. ]
# Array of 1 to 5
L3 = np.linspace(start=1, stop=5, endpoint=True, retstep=False)
print(L3, end = " ") [1. 1.08163265 1.16326531 1.24489796 1.32653061 1.40816327
1.48979592 1.57142857 1.65306122 1.73469388 1.81632653 1.89795918
1.97959184 2.06122449 2.14285714 2.2244898 2.30612245 2.3877551
2.46938776 2.55102041 2.63265306 2.71428571 2.79591837 2.87755102
2.95918367 3.04081633 3.12244898 3.20408163 3.28571429 3.36734694
3.44897959 3.53061224 3.6122449 3.69387755 3.7755102 3.85714286
3.93877551 4.02040816 4.10204082 4.18367347 4.26530612 4.34693878
4.42857143 4.51020408 4.59183673 4.67346939 4.75510204 4.83673469
4.91836735 5. ]
(array([1. , 1.08163265, 1.16326531, 1.24489796, 1.32653061,
1.40816327, 1.48979592, 1.57142857, 1.65306122, 1.73469388,
1.81632653, 1.89795918, 1.97959184, 2.06122449, 2.14285714,
2.2244898 , 2.30612245, 2.3877551 , 2.46938776, 2.55102041,
2.63265306, 2.71428571, 2.79591837, 2.87755102, 2.95918367,
3.04081633, 3.12244898, 3.20408163, 3.28571429, 3.36734694,
3.44897959, 3.53061224, 3.6122449 , 3.69387755, 3.7755102 ,
3.85714286, 3.93877551, 4.02040816, 4.10204082, 4.18367347,
4.26530612, 4.34693878, 4.42857143, 4.51020408, 4.59183673,
4.67346939, 4.75510204, 4.83673469, 4.91836735, 5. ]), 0.08163265306122448)
Specifying Endpoint - endpoint=True, include 5 - endpoint=False,exclude 5
Specifying Retstep - retstep=False, doesn’t return the step value - endpoint=False, returns the samples as well step value
logspace()np.logspace(start, stop, num, endpoint, base, dtype, retstep)
array([1.00000000e+01, 1.77827941e+03, 3.16227766e+05, 5.62341325e+07,
1.00000000e+10])
full()fill_value.np.full(shape,fill_value, dtype)
(2, 3) or 2.eye()k-th diagonal, whose values are equal to onenp.eye(N, M, k, dtype)
N.np.random.rand(shape)
[0.81734336 0.92165032 0.58365094 0.22109209 0.63737478]
[[0.75300779 0.36344641 0.30953108 0.84695505 0.42528285]
[0.81273348 0.82219856 0.03325799 0.44774794 0.8389878 ]
[0.41626324 0.23559528 0.76594982 0.70132042 0.60295411]
[0.61553901 0.78857611 0.77335201 0.16205083 0.87425881]]
[[1.54884886e+01 2.22758063e+01 6.26157575e+01 3.36928618e+01
3.92199658e+01 9.55277808e+01 9.92941007e+01]
[8.17944585e+01 8.50172709e+01 3.50931455e+01 9.48876561e+01
8.57677696e+01 7.11938563e+01 9.43478011e+01]
[5.79938042e+01 8.10532498e+01 1.51207225e+01 5.52948717e+01
4.24288778e+01 1.32168619e+01 2.38567363e+00]
[9.24917524e-02 7.48348570e+01 8.33249428e+01 4.51109040e+01
3.06106890e+01 9.00640398e+01 1.85077679e+01]
[4.16978708e+01 5.36294829e+01 4.81618167e+00 4.81639838e+01
7.12982899e+01 7.06559008e+01 1.73322906e+01]
[6.73487371e+01 5.43246986e+00 2.99953686e+00 2.03664622e+01
6.49524747e+01 7.07364923e+01 9.19542908e+00]]
empty()np.empty(shape, dtype)
SEE MORE - https://numpy.org/devdocs/user/basics.types.html
strings - used to represent text data, the text is given under quote marks. eg. “ABCD”integer - used to represent integer numbers. eg. -1, -2, -3float - used to represent real numbers. eg. 1.2, 42.42boolean - used to represent True or False.complex - used to represent a number in complex plain. eg. 1.0 + 2.0j, 1.5 + 2.5ji - integerb - booleanu - unsigned integerf - floatc - complex floatm - timedeltaM - datetimeO - objectS - stringU - unicode stringV - fixed chunk of memory for other type ( void )| Data Type | Description |
|---|---|
| bool_ | Boolean (True or False) stored as a byte |
| int_ | Default integer type (same as C long; normally either int64 or int32) |
| intc | Identical to C int (normally int32 or int64) |
| intp | Integer used for indexing (same as C ssize_t; normally either int32 or int64) |
| int8 | Byte (-128 to 127) |
| int16 | Integer (-32768 to 32767) |
| int32 | Integer (-2147483648 to 2147483647) |
| int64 | Integer (-9223372036854775808 to 9223372036854775807) |
| Data Type | Description |
|---|---|
| uint8 | Unsigned integer (0 to 255) |
| uint16 | Unsigned integer (0 to 65535) |
| uint32 | Unsigned integer (0 to 4294967295) |
| uint64 | Unsigned integer (0 to 18446744073709551615) |
| float_ | Shorthand for float64 |
| float16 | Half precision float: sign bit, 5 bits exponent, 10 bits mantissa |
| float32 | Single precision float: sign bit, 8 bits exponent, 23 bits mantissa |
| float64 | Double precision float: sign bit, 11 bits exponent, 52 bits mantissa |
| complex_ | Shorthand for complex128. |
| complex64 | Complex number, represented by two 32-bit floats |
| complex128 | Complex number, represented by two 64-bit floats |
The NumPy array object has a property called dtype that returns the data type of the array:
We use the array() function to create arrays, this function can take an optional argument: dtype that allows us to define the expected data type of the array elements
[1. 2. 3. 4. 5.]
astype()[1. 2. 3. 4. 5.]
[1 2 3 4 5]
One-dimensional arrays can be indexed, sliced and iterated over, much like lists and other Python sequences. The (start:stop:step) notation for slicing is used.
iith element of an arrayarray[i][i][j][i][j] element of an arrayarray[i][j]Note
A2[0] = [0, 1, 3], which is the first row of array A2A2[0] select the first element of first row.array([['Alice', 'Beth', 'Cathy', 'Dorothy'],
['65', '78', '90', '81'],
['71', '82', '79', '92']], dtype='<U11')
This will consider the rows 0 and 1, columns 2 and 3
array([['Beth', 'Cathy'],
['78', '90'],
['82', '79']], dtype='<U11')
array([['Alice', 'Beth', 'Cathy', 'Dorothy'],
['65', '78', '90', '81'],
['71', '82', '79', '92']], dtype='<U11')
Slicing can also include ellipsis (…) to make a selection tuple of the same length as the dimension of an array. The dots (…) represent as many colons as needed to produce a complete indexing tuple
Select row 0 and all columns
NumPy arrays can be indexed with slices, but also with boolean or integer arrays (masks). It means passing an array of indices to access multiple array elements at once. This method is called fancy indexing. It creates copies not views.
Suppose we want to access three different elements. We could do it like this:
Alternatively, we can pass a single list or array of indices to obtain the same result:
Notice that the first value in the result is food[0,0], next is food[0,3] , food[2,0] and lastly food[2,3]
Just as fancy indexing can be used to access parts of an array, it can also be used to modify parts of an array.
When we index arrays with arrays of (integer) indices we are providing the list of indices to pick. With boolean indices the approach is different; we explicitly choose which items in the array we want and which ones we don’t.
Frequently this type of indexing is used to select the elements of an array that satisfy some condition
We can do all of the above in a single concise statement
array([[ True, True, True, True],
[ True, True, False, False],
[False, False, False, False],
[False, False, False, False]])
Structured arrays or record arrays are useful when you perform computations, and at the same time you could keep closely related data together. Structured arrays provide efficient storage for compound, heterogeneous data.
NumPy also provides powerful capabilities to create arrays of records, as multiple data types live in one NumPy array. However, one principle in NumPy that still needs to be honored is that the data type in each field (think of this as a column in the records) needs to be homogeneous.
Imagine that we have several categories of data on a number of students say, name, roll number, and test scores.
There’s nothing here that tells us that the three arrays are related; it would be more natural if we could use a single structure to store all of this data.
array([('', 0, 0.), ('', 0, 0.), ('', 0, 0.), ('', 0, 0.)],
dtype=[('name', '<U10'), ('studentId', '<i4'), ('score', '<f8')])
Now that we’ve created an empty container array, we can fill the array with our lists of values
If you index student_data at position 1 you get a structure:
Note that if you’d like to do any operations that are any more complicated than these, you should probably consider the Pandas package with provides a powerful data structure called data frames.
Iterating over multidimensional arrays is done with respect to the first axis:
If one wants to perform an operation on each element in the array, one can use the flatten function which will flatten the array to a single dimension.
By default, the flattening will occur row-wise (also knows as C order)
Alice Beth Cathy Dorothy 65 78 90 81 71 82 79 92
To flatten a 2D array column-wise, use the Fortran order
Efficient multi-dimensional iterator object to iterate over arrays
This is row-wise iteration, similar to iterating over a C-order flattened array
This is like iterating over an array which has been flattened column-wise
There are a number of flags which we can pass as a list to nditer. Many of these involve setting buffering options
If we want iterate over each column, we can use the flag argument with value ‘external_loop’
By default, the nditer treats the input array as a read-only object. To modify the array elements, you must specify either read-write or write-only mode. This is controlled with per-operand flags.
np.copy(array)array.view(np.dtype)array.sort()
array([[1, 3, 4],
[5, 8, 9]])
r rows, c columns without changing dataReshape
rxc and fills new values with 0array([['Germany', 'France', 'Hungary', 'Austria'],
['Berlin', 'Paris', 'Budapest', 'Vienna']], dtype='<U8')
The primary functional difference is that flatten is a method of an ndarray object and hence can only be called for true numpy arrays. In contrast ravel() is a library-level function and hence can be called on any object that can successfully be parsed. For example ravel() will work on a list of ndarrays, while flatten will not.
array([['Germany', 'Berlin'],
['France', 'Paris'],
['Hungary', 'Budapest'],
['Austria', 'Vienna']], dtype='<U8')
reshape() gives a new shape to an array without changing its data.
array([['Germany', 'France'],
['Hungary', 'Austria'],
['Berlin', 'Paris'],
['Budapest', 'Vienna']], dtype='<U8')
Reshaping a 15-element array to an 18-element one will throw an error
Another way we can reshape is by metioning only one dimension, and -1. -1 means that the length in that dimension is inferred
array(['Germany', 'France', 'Hungary', 'Austria', 'Italy', 'Denmark'],
dtype='<U7')
array([['Germany', 'France', 'Hungary'],
['Austria', 'Italy', 'Denmark']], dtype='<U7')
If the dimensions of two arrays are dissimilar, element-to-element operations are not possible. However, operations on arrays of non-similar shapes is still possible in NumPy, because of the broadcasting capability. We will see what broadcasting is in the upcoming lessons.
A:
[[1 1]
[0 1]]
B:
[[2 0]
[3 4]]
By default, these operations apply to the array as though it were a list of numbers, regardless of its shape. However, by specifying the axis parameter you can apply an operation along the specified axis of an array
In a 2D array axis #0 represents columns. Axis #1 refers to rows
Split an array into multiple sub-arrays. By specifying the number of equally shaped arrays to return, or by specifying the columns after which the division should occur
split(array, indices_or_sections, axis=0)
Or Numpy will complain that an even split is not possible np.split(x, 4)
The numpy.hsplit is a special case of split() function where axis is 1 indicating a horizontal split regardless of the dimension of the input array.
In this example, the split will be performed along a column
array([['Germany', 'France', 'Hungary', 'Austria'],
['Berlin', 'Paris', 'Budapest', 'Vienna']], dtype='<U8')
vsplit splits along the vertical axis
An alternative approach is array unpacking. In this example, we unpack the array into two variables. The array unpacks by row i.e Unpacking “unpacks” the first dimensions of an array
When the contents are physically stored in another location, it is called Copy.
On the other hand, a different view of the same memory content is provided, we call it as View.
Different array objects can share the same data. NumPy has ndarray.view() method which is a new array object that looks at the same data of the original array.
Here, change in dimensions of the new array doesn’t change dimensions of the original.
We will create basket now as a view of fruits
print("ids for the arrays are different.")
print("id for fruits is : ")
print(id(fruits))
print("id for baskets is : ")
print(id(basket_1))
print(id(basket_2))ids for the arrays are different.
id for fruits is :
2630436222704
id for baskets is :
2630436223760
2630436223568
Here, we assign a new value to the first element of basket_2. You might be astonished that the list of fruits has been “automatically” changed as well. The explanation is that there has been no new assignment to basket_2, only to one of its elements.
In this case, a new memory location had been allocated for basket_1, because we have assigned a complete new list to this variable
The copy() method makes a complete copy of the array and its data, and doesn’t share with the original array.
We now Create a deep copy of fruits
Shape of basket:
[['Strawberry' 'Mango']
['Grapes' 'Watermelon']]
Broadcasting is a powerful mechanism that allows numpy to work with arrays of different shapes when performing arithmetic operations.
Broadcasting solves the problem of arithmetic between arrays of differing shapes by in effect replicating the smaller array along the last mismatched dimension.
NumPy operations are usually done on pairs of arrays on an element-by-element basis. In the simplest case, the two arrays must have exactly the same shape, as in the following example:
If the dimensions of two arrays are dissimilar, element-to-element operations are not possible. However, operations on arrays of non-similar shapes is still possible in NumPy, because of the broadcasting capability. The smaller array is broadcast to the size of the larger array so that they have compatible shapes.
A single value or scalar can be used in arithmetic with a one-dimensional array.
The result is equivalent to the previous example where b was an array. We can think of the scalar c being stretched during the arithmetic operation into an array with the same shape as a. The new elements in c are simply copies of the original scalar.
A scalar value can be used in arithmetic with a n-dimensional array.
A one-dimensional array can be used in arithmetic with a n-dimensional array.
Consider the following example: We have the heights (in cm) and weights ( in pounds) of a group of students. We store this information in an array called student_bio. * Heights are in cm * Weights are in kgs
When operating on two arrays, NumPy compares their shapes element-wise. The dimensions are considered in reverse order, starting with the trailing dimensions, and working its way forward. Two dimensions are compatible when
This fails because there is a mismatch in the trailing dimensions
student bio: 2 x 6
factor_1: 2
The trailing dimensions here are 6 and 2, so there is a mismatch
The dimensions are:
2 x 6
2 x 1
Here, the last dimensions are 6,1 so they match on account of one of them being 1
The next dimensions are 2,2 so there is a match
Broadcasting is possible only when certain rules are satisfied, it does not work for all cases, and imposes a strict rule that must be satisfied for broadcasting to be performed.
The dimensions with size 1 are stretched or “copied” to match the other.
After application of the broadcasting rules, the sizes of all arrays must match.
In the above example, factor is stretched to match with the dimensions of students_bio in order to carry out operations.
The arrays must have the same shape, except in the dimension corresponding to axis. The default axis along which the arrays will be joined is 0.
Joining two arrays along axis 0
array([['Germany', 'France'],
['Berlin', 'Paris'],
['Hungary', 'Austria'],
['Budapest', 'Vienna']], dtype='<U8')
array([['1', '2', '3', '4'],
['Alice', 'Beth', 'Cathy', 'Dorothy'],
['65', '78', '90', '81']], dtype='<U11')
array([['1', 'Alice', '65'],
['2', 'Beth', '78'],
['3', 'Cathy', '90'],
['4', 'Dorothy', '81']], dtype='<U11')
Stacks row wise
Stacks column wise
array(['1', '2', '3', '4', 'Alice', 'Beth', 'Cathy', 'Dorothy', '65',
'78', '90', '81'], dtype='<U11')
The functions concatenate, stack and block provide more general stacking and concatenation operations.
NumPy provides standard trigonometric functions, functions for arithmetic operations, handling complex numbers, statistical functions,etc. In NumPy, these are called “universal functions”(ufunc).
Only then can we appy trigonometric functions to our array
array([0. , 0.52359878, 0.78539816, 1.04719755, 1.57079633])
array([0. , 0.52359878, 0.78539816, 1.04719755, 1.57079633])
Cosine of angles in the array:
[1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01
6.12323400e-17]
arcsin, arcos, and arctan functions return the trigonometric inverse of sin, cos, and tan of the given angle. The result of these functions can be verified by numpy.degrees() function by converting radians to degrees.
Mean test scores of the students:
38.91625
Returns the indices of the maximum values along an axis.
Returns the indices of the minimum values along an axis.
Returns the indices that would sort an array.
Perform an indirect sort along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as a that index data along the given axis in sorted order.
array([ 11400., 11642., 12000., ..., 680000., 820000., 850000.])
The functions max , min , sort gives the respective elements itself instead of indices.
The where() function returns the indices of elements in an input array where the given condition is satisfied.
(array([ 22, 27, 33, 45, 48, 59, 77, 78, 87, 91, 94,
102, 109, 117, 123, 151, 221, 236, 242, 243, 246, 271,
296, 297, 303, 337, 343, 378, 385, 389, 402, 408, 432,
436, 450, 454, 503, 504, 538, 560, 563, 580, 581, 602,
607, 687, 701, 728, 736, 745, 769, 779, 802, 819, 822,
829, 859, 913, 922, 946, 949, 977, 980, 998, 1019, 1033,
1062, 1065, 1104, 1105, 1112, 1130], dtype=int64),)
array([261546., 500000., 120000., 210000., 105227., 115000., 130773.,
103529., 119875., 132000., 141671., 109100., 550000., 180000.,
220000., 109294., 135380., 103529., 120000., 185000., 850000.,
181339., 111600., 102000., 625000., 110464., 102000., 140000.,
120000., 820000., 250000., 130000., 136375., 141000., 142800.,
116626., 110000., 130000., 444000., 116000., 110000., 113996.,
160000., 150000., 108000., 120000., 120000., 220000., 117701.,
120000., 120010., 110000., 103645., 102000., 108977., 680000.,
152568., 114800., 150000., 111841., 110000., 108000., 102000.,
134449., 120000., 101349., 120000., 250000., 175000., 261546.,
120000., 103000.])
The extract() function returns the elements satisfying any condition
array([ 60000., 58000., 56967., 70000., 75000., 62000., 56000.,
261546., 77000., 500000., 77570., 60000., 65000., 60000.,
120000., 81000., 75000., 75000., 73000., 75000., 210000.,
90000., 105227., 84000., 98000., 70000., 115000., 72000.,
57400., 70000., 71796., 130773., 103529., 57000., 70000.,
75000., 57000., 119875., 60000., 132000., 100000., 141671.,
87500., 90000., 65000., 109100., 98080., 87689., 550000.,
56697., 60000., 180000., 92000., 63000., 220000., 66000.,
80000., 65460., 65000., 109294., 70000., 57758., 75000.,
75000., 62662., 64000., 90000., 60000., 60000., 70000.,
63000., 80000., 70000., 60000., 90000., 135380., 65000.,
70000., 103529., 64000., 70000., 120000., 185000., 70000.,
850000., 61500., 60000., 63000., 181339., 75665., 58000.,
57000., 100000., 65000., 62662., 90000., 70835., 75000.,
111600., 102000., 60000., 65000., 625000., 100000., 78000.,
75000., 60000., 64000., 63000., 59656., 69000., 80750.,
84703., 110464., 102000., 56732., 63000., 62000., 60000.,
70151., 60000., 56400., 65000., 140000., 75000., 65000.,
120000., 820000., 80000., 250000., 58000., 130000., 85000.,
60000., 65000., 71925., 136375., 90000., 141000., 90000.,
65000., 66000., 72000., 65000., 142800., 68000., 116626.,
65000., 56000., 57758., 58000., 60000., 60000., 97000.,
67382., 90000., 85000., 75000., 57000., 60000., 76600.,
60000., 110000., 130000., 61398., 60000., 65000., 70000.,
100000., 59000., 57000., 60000., 76000., 60000., 88000.,
444000., 59000., 70000., 72000., 100000., 70000., 116000.,
65000., 110000., 70000., 82000., 56000., 60000., 72000.,
60000., 70000., 113996., 160000., 60000., 81733., 66000.,
80000., 66000., 150000., 56000., 108000., 62031., 100000.,
60000., 68000., 60000., 60000., 60000., 90000., 61700.,
75000., 77000., 96000., 60000., 86000., 68000., 63000.,
65000., 60000., 90000., 90000., 80000., 63000., 80000.,
70915., 120000., 73500., 60000., 60000., 120000., 56000.,
84396., 95000., 94704., 71000., 70000., 60000., 220000.,
117701., 57758., 80000., 65000., 72000., 70000., 120000.,
60000., 60000., 63500., 60000., 59640., 61027., 70000.,
61800., 120010., 83500., 75000., 72000., 84000., 110000.,
60005., 59500., 70518., 66000., 58000., 70000., 99500.,
66858., 103645., 77000., 56000., 62000., 60000., 57400.,
92735., 58000., 69000., 102000., 68000., 108977., 75653.,
68000., 59938., 680000., 56967., 57600., 75000., 60000.,
60000., 58000., 152568., 98324., 65000., 63605., 82000.,
57000., 62000., 85000., 60000., 62500., 68656., 87280.,
60000., 57400., 76000., 63207., 59000., 114800., 60000.,
72000., 150000., 70000., 60000., 57000., 70000., 59938.,
111841., 110000., 63000., 63207., 59000., 64000., 58000.,
75000., 75000., 70500., 61000., 60555., 108000., 60000.,
80000., 102000., 100000., 64800., 62000., 134449., 75000.,
70000., 65000., 94000., 65000., 60000., 120000., 80000.,
95000., 65000., 101349., 74000., 70000., 76289., 95000.,
78000., 72000., 92000., 65000., 120000., 72000., 250000.,
68500., 62000., 81000., 70000., 84000., 56000., 87689.,
175000., 261546., 59000., 56000., 120000., 82000., 70000.,
71380., 62000., 100000., 80000., 103000., 57000., 76800.,
75000., 90000., 70000.])
vectors
See More * https://www.mathsisfun.com/algebra/vectors.html * https://en.wikipedia.org/wiki/Euclidean_vector
matrix
You can think of an r x c matrix as a set of r row vectors, each having c elements; or you can think of it as a set of c column vectors, each having r elements.
The rank of a matrix is defined as (a) the maximum number of linearly independent column vectors in the matrix or (b) the maximum number of linearly independent row vectors in the matrix. Both definitions are equivalent.
If r is less than c, then the maximum rank of the matrix is r.
If r is greater than c, then the maximum rank of the matrix is c.
matrix()np.matrix(data)array()np.array(object)mat.shape
array.sizeinsert()np.insert(matrix, object, values, axis)
[[ 1 2 3 4]
[ 4 5 6 7]
[ 7 8 9 10]]
[[ 1 1 2 3 4]
[ 1 4 5 6 7]
[ 1 7 8 9 10]]
indexmat[row_index, col_index)[[ 1 2 3 4 5]
[ 5 6 7 8 9]
[ 9 10 11 12 13]]
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]
[16 17 18 19]]
np.add()- performs element-wise addition between two matricesnp.add(matrix_1, matrix_2) np.subtract() - performs element-wise subtraction between two matrices.np.subtract(matrix_1, matrix_2) np.transpose() - Permute the dimensions of an array.np.transpose(matrix) [[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]
[16 17 18 19]]
np.dot() - performs matrix multiplication between two matrices.np.dot(matrix_1, matrix_2) Note - For matrix multiplication the number of columns in matrix \(A\) should be equal to the number of rows in matrix \(B\) - Here, Order of matrix \(A\) = \(5 \times 4\) and order of matrix \(B\) = \(5 \times 4\) - So, \(5 \neq 4\) - That’s why it shows ValueError: shapes (5,4) and (5,4) not aligned: 4 (dim 1) != 5 (dim 0)
array([[ 134, 158, 182, 206, 230],
[ 478, 566, 654, 742, 830],
[ 822, 974, 1126, 1278, 1430],
[1166, 1382, 1598, 1814, 2030],
[1510, 1790, 2070, 2350, 2630]])
array([[ 134, 158, 182, 206, 230],
[ 478, 566, 654, 742, 830],
[ 822, 974, 1126, 1278, 1430],
[1166, 1382, 1598, 1814, 2030],
[1510, 1790, 2070, 2350, 2630]])
np.multiply() - performs element-wise multiplication between two matrices.np.multiply(matrix1, matrix2)np.divide() - performs element-wise division between two matrices.np.divide(matrix_1, matrix_2)np.sum(array); array-wise sumnp.sum(array, axis=0); row-wise sumnp.sum(array, axis=1); column-wise sum Axis 0 is thus the first dimension (the “rows”), and axis 1 is the second dimension (the “columns”)
Compute the median along the specified axis.
Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values re used for integer inputs.
np.mean(array); array-wise meannp.mean(array, axis=0); row-wise meannp.mean(array, axis=1); column-wise meanCompute the median along the specified axis.
Returns the median of the array elements.
np.median(array); array-wise mediannp.median(array, axis=0); row-wise mediannp.median(array, axis=1); column-wise medianReturn the minimum of an array or minimum along an axis.
np.min(array); array-wise minnp.min(array, axis=0); row-wise minnp.min(array, axis=1); column-wise minReturn the maximum of an array or minimum along an axis.
np.max(array); array-wise maxnp.max(array, axis=0); row-wise maxnp.max(array, axis=1); column-wise maxnp.max(array) - np.min(array)np.std(array); array-wise stdnp.std(array, axis=0); row-wise stdnp.std(array, axis=1); column-wise stdnp.var(array); array-wise varnp.var(array, axis=0); row-wise varnp.var(array, axis=1); column-wise varnp.quantile(array); array-wise quantilenp.quantile(array, axis=0); row-wise quantilenp.quantile(array, axis=1); column-wise quantileLinear algebra is the branch of mathematics concerning linear equations such as linear maps such as and their representations in vector spaces and through matrices. Linear algebra is central to almost all areas of mathematics See More
SEE DETAILS: https://www.analyticsvidhya.com/blog/2019/07/10-applications-linear-algebra-data-science/
The determinant of a matrix is a special number that can be calculated from a square matrix \[\begin{equation} A = \begin{bmatrix} a & b \\ c & d \end{bmatrix} \\ det(A) = ad - bc \end{equation}\] Whre, A is a \(2 \times 2\) matrix.
np.linalg.det() - performs determinant of the matrix
Syntax: np.linalg.det(matrix)
Source: https://www.mathsisfun.com/algebra/matrix-determinant.html
[[ 4 5 16 7]
[ 2 -3 2 3]
[ 3 4 5 6]
[ 4 7 8 9]]
np.linalg.matrix_rank() - returns rank of the matrixnp.linalg.matrix_rank(matrix)np.linalg.inv() - returns the multiplicative inverse of a matrix.np.linalg.inv(matrix)matrix([[ 9.37500000e-02, -4.68750000e-01, 3.68750000e+00,
-2.37500000e+00],
[ 3.53252781e-17, -2.50000000e-01, 5.00000000e-01,
-2.50000000e-01],
[ 9.37500000e-02, 3.12500000e-02, -3.12500000e-01,
1.25000000e-01],
[-1.25000000e-01, 3.75000000e-01, -1.75000000e+00,
1.25000000e+00]])
matrix([[ 1.50000000e+00, -2.08166817e-17, -1.00000000e+00,
-5.00000000e-01],
[ 2.50000000e-01, -1.66666667e-01, -3.33333333e-01,
8.33333333e-02],
[ 1.00000000e+00, 3.33333333e-01, -3.33333333e+00,
1.33333333e+00],
[-1.75000000e+00, -1.66666667e-01, 3.66666667e+00,
-9.16666667e-01]])
Consider a system of equations \[3x + y + 2z = 2\] \[3x + 2y + 5z = -1\] \[6x + 7y + 8z = 3\]
Now we can write the equations in the form of \(Ax = b\)
np.linalg.matrix_rank() - returns rank of the matrixnp.linalg.matrix_rank(matrix)Manish Patel